package com.hmdp.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

/**
 * 唯一ID生成器
 */
@Component
@Slf4j
public class RedisIdWorker {
    /**
     * 开始时间戳
     */
    private static final long BEGIN_TIMESTAMP = 1704067200;
    private static final int COUNT_BITS = 32;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    public long nextId(String keyPrefix) {
        // 1.生成时间戳
        LocalDateTime now = LocalDateTime.now();
        long nowSecond = LocalDateTime.now().toEpochSecond(ZoneOffset.UTC);//获取当前时间戳
        long timestamp = nowSecond - BEGIN_TIMESTAMP;//得到时间戳（当前减去开始）
        // 2.自增长，生成序列号,不能使用同一个key加上时间
        String date = now.format(DateTimeFormatter.ofPattern("yyyy:MM:dd"));
        Long count = stringRedisTemplate.opsForValue().increment("icr:" + keyPrefix + ":" + date);
        // 3.拼接并返回
        //让timestamp向左移动32位拼接count
        return timestamp << COUNT_BITS | count;

    }

    /**
     * 获取开始时间戳
     * @param args
     */
    public static void main(String[] args) {
        //生成初始时间
        LocalDateTime time = LocalDateTime.of(2024, 1, 1, 0, 0, 0);
        //得到秒数，ZoneOffset.UTC是时区
        long second = time.toEpochSecond(ZoneOffset.UTC);

        System.out.println("second="+second);

    }
}
